const { query } = require('../config/db');

class MiniappImage {
  /**
   * 获取所有小程序图片配置
   * @param {Object} options - 查询选项
   * @returns {Promise<Array>} 图片配置列表
   */
  static async findAll(options = {}) {
    const { page_name, image_type, is_active } = options;
    
    let sql = 'SELECT * FROM miniapp_images WHERE 1=1';
    const params = [];
    
    if (page_name) {
      sql += ' AND page_name = ?';
      params.push(page_name);
    }
    
    if (image_type) {
      sql += ' AND image_type = ?';
      params.push(image_type);
    }
    
    if (is_active !== undefined) {
      sql += ' AND is_active = ?';
      params.push(is_active);
    }
    
    sql += ' ORDER BY sort_order ASC, created_at DESC';
    
    return await query(sql, params);
  }

  /**
   * 根据页面名称获取图片配置
   * @param {string} pageName - 页面名称
   * @returns {Promise<Array>} 图片配置列表
   */
  static async findByPageName(pageName) {
    const sql = 'SELECT * FROM miniapp_images WHERE page_name = ? AND is_active = 1 ORDER BY sort_order ASC';
    return await query(sql, [pageName]);
  }

  /**
   * 根据图片键获取单个图片配置
   * @param {string} imageKey - 图片配置键
   * @returns {Promise<Object|null>} 图片配置对象
   */
  static async findByKey(imageKey) {
    const sql = 'SELECT * FROM miniapp_images WHERE image_key = ?';
    const results = await query(sql, [imageKey]);
    return results.length > 0 ? results[0] : null;
  }

  /**
   * 根据ID获取单个图片配置
   * @param {number} id - 图片配置ID
   * @returns {Promise<Object|null>} 图片配置对象
   */
  static async findById(id) {
    const sql = 'SELECT * FROM miniapp_images WHERE id = ?';
    const results = await query(sql, [id]);
    return results.length > 0 ? results[0] : null;
  }

  /**
   * 创建新的图片配置
   * @param {Object} imageData - 图片配置数据
   * @returns {Promise<Object>} 创建的图片配置对象
   */
  static async create(imageData) {
    const {
      image_key,
      image_name,
      image_url,
      image_type = 'icon',
      page_name,
      sort_order = 99,
      is_active = true,
      description = ''
    } = imageData;

    const sql = `
      INSERT INTO miniapp_images 
      (image_key, image_name, image_url, image_type, page_name, sort_order, is_active, description)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const result = await query(sql, [
      image_key, image_name, image_url, image_type, 
      page_name, sort_order, is_active, description
    ]);
    
    return await this.findById(result.insertId);
  }

  /**
   * 更新图片配置
   * @param {number} id - 图片配置ID
   * @param {Object} updateData - 更新数据
   * @returns {Promise<Object|null>} 更新后的图片配置对象
   */
  static async update(id, updateData) {
    const allowedFields = [
      'image_name', 'image_url', 'image_type', 'page_name', 
      'sort_order', 'is_active', 'description'
    ];
    
    const updateFields = [];
    const updateValues = [];
    
    for (const field of allowedFields) {
      if (updateData.hasOwnProperty(field)) {
        updateFields.push(`${field} = ?`);
        updateValues.push(updateData[field]);
      }
    }
    
    if (updateFields.length === 0) {
      throw new Error('没有可更新的字段');
    }
    
    updateValues.push(id);
    
    const sql = `UPDATE miniapp_images SET ${updateFields.join(', ')} WHERE id = ?`;
    await query(sql, updateValues);
    
    return await this.findById(id);
  }

  /**
   * 删除图片配置
   * @param {number} id - 图片配置ID
   * @returns {Promise<boolean>} 删除是否成功
   */
  static async delete(id) {
    const sql = 'DELETE FROM miniapp_images WHERE id = ?';
    const result = await query(sql, [id]);
    return result.affectedRows > 0;
  }

  /**
   * 批量更新排序
   * @param {Array} sortData - 排序数据 [{id, sort_order}, ...]
   * @returns {Promise<boolean>} 更新是否成功
   */
  static async updateSort(sortData) {
    const promises = sortData.map(item => {
      const sql = 'UPDATE miniapp_images SET sort_order = ? WHERE id = ?';
      return query(sql, [item.sort_order, item.id]);
    });
    
    await Promise.all(promises);
    return true;
  }

  /**
   * 获取图片配置的统计信息
   * @returns {Promise<Object>} 统计信息
   */
  static async getStats() {
    const totalSql = 'SELECT COUNT(*) as total FROM miniapp_images';
    const activeSql = 'SELECT COUNT(*) as active FROM miniapp_images WHERE is_active = 1';
    const pagesSql = 'SELECT page_name, COUNT(*) as count FROM miniapp_images GROUP BY page_name';
    const typesSql = 'SELECT image_type, COUNT(*) as count FROM miniapp_images GROUP BY image_type';
    
    const [totalResult, activeResult, pagesResult, typesResult] = await Promise.all([
      query(totalSql),
      query(activeSql),
      query(pagesSql),
      query(typesSql)
    ]);
    
    return {
      total: totalResult[0].total,
      active: activeResult[0].active,
      byPage: pagesResult,
      byType: typesResult
    };
  }

  /**
   * 检查图片键是否已存在
   * @param {string} imageKey - 图片配置键
   * @param {number} excludeId - 排除的ID（用于更新时检查）
   * @returns {Promise<boolean>} 是否已存在
   */
  static async keyExists(imageKey, excludeId = null) {
    let sql = 'SELECT COUNT(*) as count FROM miniapp_images WHERE image_key = ?';
    const params = [imageKey];
    
    if (excludeId) {
      sql += ' AND id != ?';
      params.push(excludeId);
    }
    
    const result = await query(sql, params);
    return result[0].count > 0;
  }

  /**
   * 获取小程序所有页面的图片配置（用于小程序端）
   * @returns {Promise<Object>} 按页面分组的图片配置
   */
  static async getAllForMiniapp() {
    const sql = `
      SELECT image_key, image_name, image_url, image_type, page_name, sort_order
      FROM miniapp_images 
      WHERE is_active = 1 
      ORDER BY page_name, sort_order ASC
    `;
    
    const images = await query(sql);
    
    // 按页面分组
    const result = {};
    images.forEach(image => {
      if (!result[image.page_name]) {
        result[image.page_name] = {};
      }
      result[image.page_name][image.image_key] = {
        name: image.image_name,
        url: image.image_url,
        type: image.image_type,
        sort_order: image.sort_order
      };
    });
    
    return result;
  }
}

module.exports = MiniappImage;
